<template>
  <q-page class="q-pa-md wrapBox" v-loading="loading">
    <div class="nav">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <el-image src="/svgs/titleIcon.svg" style="width: 17px;margin-top: 2px" fit />
        </el-breadcrumb-item>
        <el-breadcrumb-item>数据中心</el-breadcrumb-item>
        <el-breadcrumb-item><span style=" color: #333;">数据标注</span></el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="datasetBox" style="position: relative">
      <div class="contentBox_title">数据标注</div>
      <div class="contentBox">
        <el-row class="mb-4" style="margin-bottom: 15px">
          <div style="margin-top: 10px">
            <el-input
              v-model.trim="searchName"
              placeholder="搜索任务名称"
              spellcheck="false"
            >
              <template #prepend>
                <el-select v-model="typeValue" placeholder="全部" style="width: 150px;background-color: #fff">
                  <el-option
                    v-for="item in datalabelPage"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    @click="filterDataset"
                  />
                </el-select>
              </template>
              <template #append>
                <el-button :icon="Search" @click="filterDataset" />
              </template>
            </el-input>
          </div>
          <div class="rightBox">
            <el-button
              style="background-color: #3d5ce4; width: 80px;margin-top: 10px"
              type="primary" @click="toCreateDataSet">新建</el-button>
          </div>
        </el-row>
        <el-table
          ref="tabelList"
          :data="resData.results"
          style="width: 100%;font-size: 14px;"
          :cell-style="cellStyle"
          :header-cell-style="{
            background: '#f9f9f9',
            color: '#333333',
            fontWeight: '500',
            fontSize: '14px',
            textAlign: 'left',
            height: '56px'
          }"
        >
          <el-table-column align="left" prop="title" label="任务名称" width="150" />
          <el-table-column align="left" prop="label_type_zh" label="标注类型" width="150" />
          <el-table-column align="left" prop="creator" label="标注进度(已标注个数/总数)" width="200">
            <template #default="scope">
              <p style="margin: 0">{{ [((Number(scope.row.data_statistic.labeled_number) / Number(scope.row.data_statistic.total_number)) * 100).toFixed(2)] + '%' }}</p>
            </template>
          </el-table-column>
          <el-table-column align="left" prop="source" label="数据来源" width="150" />
          <el-table-column align="left" prop="description" label="描述" width="150">
            <template #default="scope">
              {{ scope.row.description?scope.row.description:'-' }}
            </template>
          </el-table-column>
          <el-table-column align="left" prop="create_time" label="创建时间" width="180" />
          <el-table-column align="left" label="操作">
            <template #default="scope">
              <el-button
                v-for="(item, index) in labelsObj "
                :key="index"
                v-show="userStatus?true:scope.row.creator === userInfoName"
                link
                style="font-size: 14px"
                type="primary"
                size="small"
                @click="labelsFun(item, scope.row.id, scope.row.labels, scope.row.annotation_config, scope.row.label_type,scope.row)">
                {{ item }}</el-button>
            </template>
          </el-table-column>
          <template #empty>
            <div class="noData">暂无数据</div>
          </template>
        </el-table>
      </div>
      <div class="row" style="justify-content:flex-end;margin-top: 10px;background-color: #fff;padding: 10px 0 " v-if="resData.results.length>0">
        <el-pagination
          background
          layout="prev, pager, next, sizes, jumper"
          :total="resData.count"
          :page-sizes="[10, 20, 50]"
          @size-change="sizeChange"
          v-model:current-page="pageData.page"
          @current-change="changePage"
        />
      </div>
    </div>
    <div style="position: relative;">
<!--      <el-row class="mb-4 " style="margin-bottom: 15px;">-->
<!--        <div>-->
<!--          <el-button style="background-color: rgb(60,145,254);width: 150px" type="primary" @click="toCreateDataSet">新建标注任务</el-button>-->
<!--        </div>-->

<!--        <div class="rightBox">-->
<!--          <el-select v-model="typeValue" class="m-2" placeholder="全部" style="margin-right: 20px;">-->
<!--            <el-option v-for="item in dataTypeData" :key="item.value" :label="item.label" :value="item.value"-->
<!--                       @click="filterDataset" />-->
<!--          </el-select>-->
<!--          <el-input v-model.trim="searchName" class="w-50 m-2" placeholder="搜索任务名称" :suffix-icon="Search"-->
<!--                    @keyup.enter="filterDataset" spellcheck="false" />-->
<!--        </div>-->
<!--      </el-row>-->

      <el-dialog v-model="dialogFormVisible" title="导入数据" width="500" :show-close="false" :close-on-click-modal="false">
        <upload-data-set v-if="dialogFormVisible" @formData="formData" :userData="listIndex"></upload-data-set>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="formDataFun">
              导入
            </el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 发布新版本 -->
      <el-dialog
        :close-on-click-modal="false"
        v-model="dialogNewVersion" title="发布数据新版本" width="400" :show-close="false"
        @close="resetForm(ruleFormRef)">
        <el-form ref="ruleFormRef" :model="formLabelAlign" :rules="rules" label-position="right" label-width="100px"
                 style="max-width: 460px">
          <el-form-item label="版本名称：" prop="title">
            <el-input v-model.trim="formLabelAlign.title" input-style="width:180px" />
          </el-form-item>
          <el-form-item label="版本描述：" prop="description">
            <el-input v-model.trim="formLabelAlign.description" input-style="width:180px" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="resetForm(ruleFormRef)" style="background-color: #fff!important;">取消</el-button>
            <el-button type="primary" @click="createNewVersion(ruleFormRef)">
              确认
            </el-button>
          </span>
        </template>
      </el-dialog>

      <!--数据集合并 start-->
      <el-dialog
        v-model="mergeDialogShow"
        title="数据集合并"
        width="600px"
        :show-close="false"
        :close-on-click-modal="false"
      >
        <el-form
          style="padding: 0 50px"
          ref="mergeFormRef"
          :model="mergeForm"
          :rules="mergeFormRules"
          :label-position="'right'"
          label-width="110px"
          status-icon
          @submit.prevent
        >
          <el-form-item label="数据集名称:" prop="name">
            <el-input v-model.trim="mergeForm.name" style="width: 100%" />
          </el-form-item>
          <el-form-item label="数据集类型:" prop="datasetType">
            <p>文本</p>
          </el-form-item>
          <el-form-item label=" 数据集说明:">
            <el-input v-model.trim="mergeForm.description" type="textarea" :rows="3" placeholder="请输入" show-word-limit maxlength="100"/>
          </el-form-item>
          <el-form-item label="输入版本号:" prop="version">
            <el-input v-model.trim="mergeForm.version" placeholder="请输入版本号,例: v1、v001" style="width: 100%" />
          </el-form-item>
        </el-form>
        <template #footer>
        <span class="dialog-footer">
          <div class="button" @click="cancelMergeForm(mergeFormRef)">取消</div>
          <div
            class="button"
            @click="mergeBtn(mergeFormRef)"
          >合并</div>
        </span>
        </template>
      </el-dialog>
      <!--数据集合并 end-->

      <!--数据处理建模 start-->
      <el-dialog
        v-model="dataProcessingModel"
        title="数据处理建模"
        width="600px"
        :show-close="false"
        :close-on-click-modal="false"
      >
        <el-form
          style="padding: 0 50px"
          ref="dataProcessingFormRef"
          :model="mergeForm"
          :rules="mergeFormRules"
          :label-position="'right'"
          label-width="110px"
          status-icon
          @submit.prevent
        >
          <el-form-item label="数据集名称：">
            <p style="margin: 0">{{ datasetTitle }}</p>
          </el-form-item>
          <el-form-item label="数据类型：">
            <p style="margin: 0">{{ datasetTypeZh }}</p>
          </el-form-item>
          <el-form-item label="版本选择：" prop="version">
            <el-select v-model="exportForm.version" class="m-2" placeholder="选择版本" style="width:300px" popper-class="dropdown">
              <el-option v-for="item in versionList" :key="item.id" :label="item.title" :value="item.title"/>
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
        <span class="dialog-footer">
          <div class="button" @click="cancelDataProcessingModel(dataProcessingFormRef)">取消</div>
          <div
            class="button"
          >进入建模</div>
        </span>
        </template>
      </el-dialog>
      <!--数据处理建模 end-->

      <!-- 删除 -->
      <q-dialog v-model="dialogDeleteData">
        <q-card style="width: 370px;">
          <q-card-section>
            <div class="text-h6" style="font-size: 17px;">
              <el-icon
                style="color: #FFA940;display: inline-block;vertical-align: middle;margin-top: -3px;font-size: 20px;">
                <WarningFilled />
              </el-icon>
              <span style="font-size: 16px;margin-left: 5px; color: #FFA940;">删除提醒</span>
            </div>
          </q-card-section>
          <q-card-section class="q-pt-none">
            <div>确定删除该标注任务吗？删除后不可恢复,请谨慎操作!</div>
          </q-card-section>
          <q-card-actions align="right" class="text-primary" style="margin-right: 10px;margin-top: 10px">
            <el-button @click="deleteData" style="background-color: #fff!important;">确认删除</el-button>
            <el-button type="primary" v-close-popup>放弃删除</el-button>
          </q-card-actions>
        </q-card>
      </q-dialog>
    </div>
  </q-page>
</template>
<script setup lang="ts">

import { ref, reactive, shallowRef, onMounted, watch, onUnmounted} from "vue"
import { Search } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import {
  getDatasetList,
  createVersion,
  exportDataSet,
  versionManage,
  getdataLabel,
  deletedataLabel,
  searchDataLabel
} from 'src/api/dataset'
import { useRouter } from 'vue-router'
import uploadDataSet from 'src/components/uploadDataSet.vue'
import { ElNotification, ElMessage } from 'element-plus'
import { dataSetStore } from 'src/stores/dataSet'
const userStatus = JSON.parse(localStorage.getItem('user') || "{}").status;//判断用户是否是项目创建人或项目管理员
const userInfoName = localStorage.getItem('username')//获取用户登录的用户名

import { batchUploadDatasetData } from 'src/api/dataset'
import { datalabelPage } from 'src/utils/useData'
const store = dataSetStore()
const router = useRouter()
const projectId = router.currentRoute.value.params.project_id
const pageData =dataSetStore().pageData
const searchName = ref('')
const listIndex = ref()
const typeValue = ref('')
const oneDataId = ref();
const datasetTitle = ref();//数据集名称
const datasetTypeZh = ref();//数据类型
const versionList = ref([]);//版本选择
const loading = ref(false)
const dialogFormVisible = ref(false)
const dialogNewVersion = ref(false)
const dialogDeleteData = ref(false)
const dataProcessingModel = ref(false);//数据处理建模
const formLabelAlign = reactive({
  title: '',
  description: '',
})
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules>({
  title: [
    { required: true, message: '版本名称不能为空', trigger: ['blur','change'] }
  ]
})
let mergeDialogShow = ref(false);//合并弹框生效
const mergeFormRef = ref();
const mergeForm = reactive({
  name: '',
  datasetType: '文本',
  description: '',
  version: ''
});
const mergeFormRules = reactive({
  name: [
    { required: true, message: '数据集名称不能为空', trigger: 'blur' },
  ],
  version: [
    { required: true, message: '版本号不能为空', trigger: 'blur' },
  ],
});
const uploadData = shallowRef({
  file_ids: <any>[],
  is_labeled: false,
  import_mode: 'local'
})

const dataProcessingFormRef = ref();//数据处理建模表单ref
const cellStyle = () =>{
  return { height: '56px' };
}
//取消数据处理建模按钮
const cancelDataProcessingModel = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  if (dataProcessingModel.value) {
    formEl.resetFields()
    dataProcessingModel.value = false
  }
}

const fileUploadState=ref(true)
function formData(e: any) {
  let urlArr = e.value.choices.map((item: any, index: number) => {
    return item.id
  })
  uploadData.value = { file_ids: urlArr, is_labeled: e.value.is_labeled, import_mode: e.value.import_mode }
  fileUploadState.value=e.value.fileUpload
}
// 切换页
function changePage(currentPage:any){
  dataSetStore().setPageData(currentPage)
  getDataset();
}
function sizeChange(pageSize:any) {
  dataSetStore().setPageData(1)
  dataSetStore().setPageSizeData(pageSize)
  getDataset();
}
// 新建数据集
function toCreateDataSet() {
  router.push({ name: 'dataAnnotations-create', params: { project_id: projectId } })
}
function formDataFun() {
  if (fileUploadState.value==true) {
    ElMessage.error('文件正在上传,请等待')
    return
  }
  if (uploadData.value.file_ids.length == 0) {
    ElMessage.error('请选择上传文件')
    return
  }

  batchUploadDatasetData(projectId, oneDataId.value, uploadData.value).then((res: any) => {
    dialogFormVisible.value = false
    ElNotification({
      title: 'Success',
      message: '导入数据成功',
      type: 'success',
    })
  }).finally(() => {
    getDataset();
    uploadData.value.file_ids = []
  })
}
// 取消创建数据集
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  if (dialogNewVersion.value) {
    formEl.resetFields()
    dialogNewVersion.value = false
  }
}

// 新建数据版本
const createNewVersion = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      createVersion(projectId, oneDataId.value, formLabelAlign).then((res: any) => {
        dialogNewVersion.value = false
        ElNotification({
          title: 'Success',
          message: '新建数据版本成功',
          type: 'success',
        })
      }).finally(()=>{
        formLabelAlign.title=' '
        formLabelAlign.description=' '
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}


let resData = reactive({
  count: 0,
  next: null,
  previous: null,
  results: []
})
const labelsObj = ref([
  '标注',
  '标签',
  '删除',
]);
onMounted(()=>{
  // 通过store.quickStart.quickFlow判断是否显示快速入门提示
  if (store.quickStart.quickFlow) {
    store.setQuickStart({
      tipsPopup: true,
      quickFlow: true,
      flowNumber: store.quickStart.flowNumber
    })
  }
  dataSetStore().setPageData(1)
  getDataset();
})
function filterDataset() {
  getDataset();
}
function getDataset() {
  loading.value = true
  let obj = {}
  if (typeValue.value != '' || searchName.value != '') obj = {label_type: typeValue.value,title: searchName.value}
  obj=Object.assign(obj,pageData);
  searchDataLabel(projectId, obj).then((res: any) => {
    resData = res.data
  }).finally(() => {
    loading.value = false
  })
}
//点击取消
const cancelMergeForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  mergeDialogShow.value = false
}
function labelsFun(str: string, id:number, labels: [], config: string, type: string,row:any) {
  oneDataId.value = id
  if( str === '标注' ) {
    dataSetStore().setUseData(id, config, type,row.title)
    dataSetStore().taskId(id)
    if(
      row.label_scene === 'image_classification' ||
      // row.label_scene === 'outliers_and_anomaly_detection' ||
      // row.label_scene === 'signal_quality' ||
      // row.label_scene === 'time_series_forecasting' ||
      row.label_scene === 'taxonomy' ||
      row.label_scene === 'text_classification'
    ){
      dataSetStore().setLabelsArr(row.choices)
    }else{
      dataSetStore().setLabelsArr(labels)
    }
    router.push({ name: 'dataAnnotations-dimension', params: { project_id: projectId } })
    // dataProcessingModel.value = true
  }
  if( str === '标签' ) {
    dataSetStore().setUseData(id, config, type,row.title)
    dataSetStore().taskId(id)
    if(
      row.label_scene === 'image_classification' ||
      // row.label_scene === 'outliers_and_anomaly_detection' ||
      // row.label_scene === 'signal_quality' ||
      // row.label_scene === 'time_series_forecasting' ||
      row.label_scene === 'taxonomy' ||
      row.label_scene === 'text_classification'
    ){
      dataSetStore().setLabelsArr(row.choices)
    }else{
      dataSetStore().setLabelsArr(labels)
    }
    router.push({ name: 'dataAnnotations-label', params: { project_id: projectId, dataset_id: '18' } })
  }
  if( str === '删除' ) dialogDeleteData.value = true
}

function deleteData() {
  deletedataLabel(projectId, oneDataId.value).then((res: any) => {
    loading.value = true
    dialogDeleteData.value = false
    ElMessage({
      message: '删除成功',
      type: 'success',
    })
  }).finally(() => {
    getdataLabelList();
    getDataset();
  }).catch((error) => {
    dialogDeleteData.value=false
  })
}
//合并数据集

const mergeBtn = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('1');
    }
  })
}

// onMounted(() => {
//   getdataLabelList()
// })

//获取数据标注任务
function getdataLabelList() {
  loading.value = true
  getdataLabel(projectId).then( res =>{
    resData = res.data;
  }).finally(() => {
    loading.value = false
  })
}
const uploadDataType = (data_type: string,label_type:string) => {
  if(label_type=='question_answering'){
    return 'json'
  }else{
    switch (data_type) {
      case 'Image':
        return 'jpg,png,gif,bmp,svg,webp,jpeg'
      case 'Text':
        return 'txt'
      case 'TimeSeries':
        return 'csv,tsv'
    }
  }

}
</script>

<style lang="scss" scoped>
.nav {
  display: flex;
  align-items: center;
  margin-left: 20px;
  cursor: pointer;
  background-color: var(--nav-bg-color);
  height: 46px;
  ::v-deep .el-breadcrumb{
    display: flex;
    align-items: center;
  }
}
.wrapBox {
  padding: 0 !important;
  .datasetBox {
    margin: 0 20px;
    .contentBox_title{
      color: var(--title);
      font-weight: 500;
      font-size: 16px;
      padding: 15px 15px;
      border-bottom: 1px solid #e5e6eb;
      background-color: #ffffff !important;
    }
    .contentBox {
      padding: 12px;
      background-color: #ffffff !important;
    }
  }
}
//面包屑斜杆
::v-deep .el-breadcrumb__separator{
  font-size: 12px!important;
  color: #c9cdd4!important;
  margin-top: 2px!important;
}
//面包屑字体颜色
::v-deep .el-breadcrumb__inner{
  color: #666!important;
}

::v-deep .el-select-dropdown__item{
  padding: 0!important;
}

::v-deep disabled,::v-deep  .disabled *, ::v-deep [disabled],::v-deep [disabled] * {
  outline: 10px !important;
  cursor: pointer !important;
}

//数据处理建模表头加下划线 start
::v-deep .el-dialog__header {
  border-bottom: 1px solid rgb(234,234,234);
}
//end

::v-deep .el-dialog__body {
  padding-top: 10px;
}


.rightBox {
  position: absolute;
  right: 0;
}

.el-dropdown {
  color: #3D5CE4;
  font-size: 12px;
  line-height: 24px;
  margin-left: 15px;
}

.deleteTip {
  .el-dialog__body {
    padding: 10px;
    text-align: center;
  }
}
.dialog-footer {
  display: flex;
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  border-top: 1px solid;
  .button {
    cursor: pointer;
    width: 50%;
    margin: 0;
    border: none;
    text-align: center;
    line-height: 40px;
  }
  .button:nth-child(1){
    color: #1d1d1d;
    border-right: 1px solid;
  }
  .button:nth-child(2){
    color: #1b5bd8;
  }
}
//公共样式
//下拉框背景颜色
.dropdown {
  .el-select-dropdown__item.selected{
    font-weight: 500!important;
  }
  .el-select-dropdown__item.hover,
  .el-select-dropdown__item:hover {
    background: #3d5ce41a;
    color: #3d5ce4;
    font-weight: 400;
    font-size: 14px;
    text-align: left;
  }
}
</style>
